﻿
CREATE PROCEDURE [usix].[s_Export_Short]
	@UsixID varchar(8),
	@CompanyID int
AS
SET NOCOUNT ON;

EXEC sp__Context_ArchiveOff 1

EXEC sh_Debug_PRINT 'usix.s_Export $0/$1',@UsixID,@CompanyID

DECLARE @LoanID varchar(50),@USIX_VIN varchar(17),@OpenField1 int,@VC bit

SELECT @LoanID = LoanID FROM t_Loan_Usix WHERE UsixID = @UsixID AND CompanyID_Raw = @CompanyID
IF @LoanID IS NULL BEGIN RAISERROR('%s,%d has not been pre-exported. Use usix.s_Export_Short_ALL.',16,1,@UsixID,@CompanyID) RETURN 0 END

EXEC sh_Debug_PRINT 'BEGIN TRAN Export for $0/$1/$2',@UsixID,@CompanyID,@USIX_VIN

SELECT @USIX_VIN = CASE dbo.clr_VINCheck(VIN) WHEN 1 THEN VIN ELSE NULL END
FROM usix.t_CustomerFile WHERE [Customer #] = @UsixID AND CompanyID_Raw = @CompanyID

BEGIN TRAN Export

IF NOT EXISTS(SELECT * FROM t_Car WHERE VIN = @USIX_VIN) AND  @USIX_VIN > ''
	INSERT INTO t_Car(VIN,Year, Make, Model, Mileage)
	SELECT CF.VIN,CF.[Car Year], CF.Make, CF.Model, CF.MILEAGE
	FROM t_Car c CROSS JOIN usix.t_CustomerFile CF
	WHERE c.VIN = @USIX_VIN AND CF.[Customer #] = @UsixID AND CF.CompanyID_Raw = @CompanyID

/**/EXEC sh_Debug_PRINT 'INSERT INTO t_Loan(StatusID)VALUES(StatusID)'
IF NOT EXISTS(SELECT * FROM t_Loan WHERE ID = @LoanID)BEGIN
	RAISERROR('Loan %d does not exists. Use usix.s_Export_Short_ALL.',16,1,@LoanID)
	RETURN 0
--	INSERT INTO t_Loan(StatusID,ApplicantID)VALUES(dbo.fs_StateID__Processing__FundedInUSIX(),@OpenField1)
--	IF @@ERROR <> 0 BEGIN ROLLBACK RETURN 0 END
--	SET @LoanID = IDENT_CURRENT('t_Loan')
END

EXEC sh_Debug_PRINT 's_Export_Short_AddOn $0,$1,$2',@UsixID,@CompanyID,@LoanID
EXEC usix.s_Export_Short_AddOn @UsixID,@CompanyID,@LoanID
IF @@ERROR <> 0 BEGIN ROLLBACK RETURN 0 END

IF @USIX_VIN > ''	UPDATE t_CarInfo SET VIN = @USIX_VIN WHERE LoanID = @LoanID AND ISNULL(VIN,'') = ''
IF @@ERROR <> 0 BEGIN ROLLBACK RETURN 0 END

COMMIT TRANSACTION Export

EXEC sp__Context_ArchiveOff 0


RETURN @LoanID

